<template>
  <MessageDialog ref="messageDialogRef" :deviceName="device.name" />
  <el-col>
    <el-row class="nodes" :span="24">
      <TextNode label="服务器地址" :name="device.ip" />
      <TextNode label="端口号" :name="String(device.port)" />
      <TextNode label="通讯类型" :name="device.protocol" />
      <!-- 新增连接状态按钮 -->
      <el-button
        :type="device.isConnected ? 'danger' : 'success'"
        @click="toggleConnection"
        style="margin-top: 15px"
      >
        {{ device.isConnected ? "断开连接" : "打开连接" }}
      </el-button>
      <el-button type="primary" @click="openMessageDialog" style="margin-top: 15px">
        <el-icon style="vertical-align: middle">
          <Setting />
        </el-icon>
        <span style="vertical-align: middle"> 查看报文 </span>
      </el-button>
    </el-row>
    <Slave :device="device" />
  </el-col>
  <div class="register-view">
    <el-tabs v-model="activeRegisterName" type="card" class="tabs">
      <el-tab-pane label="Unsigned/Signed/Hex/Binary" name="single">
        <el-scrollbar class="horizontal-scroll" always>
          <div class="register-container">
            <SingleRegister
              v-for="reg in singleRegisters"
              :key="`single_${reg[TableHeader.Address]}`"
              :register="reg"
              :isDualRegister="false"
            />
          </div>
        </el-scrollbar>
      </el-tab-pane>

      <el-tab-pane label="Long" name="long">
        <el-scrollbar class="horizontal-scroll" always>
          <div class="register-container">
            <LongRegister
              v-for="(pair, index) in longPairs"
              :key="`long_${index}`"
              :registers="pair"
              :isDualRegister="true"
            />
          </div>
        </el-scrollbar>
      </el-tab-pane>

      <el-tab-pane label="Float" name="float">
        <el-scrollbar class="horizontal-scroll" always>
          <div class="register-container">
            <FloatRegister
              v-for="(pair, index) in floatPairs"
              :key="`float_${index}`"
              :registers="pair"
              :isDualRegister="true"
            />
          </div>
        </el-scrollbar>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script lang="ts" setup>
import {ref, onMounted, watch, computed} from "vue";
import {useRoute} from "vue-router";
import TextNode from "@/components/TextNode.vue";
import Slave from "@/components/slave/Slave.vue";
import {useDeviceStore} from "@/stores/device";
import {TableHeader, type Device} from "@/types/device";
import {storeToRefs} from "pinia";
import SingleRegister from "@/components/decode_register/SingleRegister.vue";
import LongRegister from "@/components/decode_register/LongRegister.vue";
import FloatRegister from "@/components/decode_register/FloatRegister.vue";
import MessageDialog from "@/components/MessageDialog.vue";
import {Setting} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { closeConnection, openConnection } from "@/api/deviceApi";

const route = useRoute();
const routeName = ref(route.name as string);
const deviceStore = useDeviceStore();
const device = ref<Device>({
  id: 0,
  name: "Unknown",
  ip: "0.0.0.0",
  port: 0,
  protocol: "Unknown",
  isConnected: false,
});
const messageDialogRef = ref<typeof MessageDialog>();

const {selectedRows} = storeToRefs(deviceStore); // 解构保持响应式
const activeRegisterName = ref("single");

// 切换连接状态的方法
const toggleConnection = async () => {
  if (device.value.isConnected) {
    const isSuccess = await closeConnection(device.value.name).catch(() => false);
    if (!isSuccess) {
      ElMessage.error('断开连接失败');
      return;
    }else{
      device.value.isConnected = false;
      ElMessage.success('连接已断开');
    }
  } else {
    const isSuccess = await openConnection(device.value.name).catch(() => false);
    if (!isSuccess) {
      ElMessage.error('打开连接失败');
      return;
    }else{
      device.value.isConnected = true;
      ElMessage.success('连接已打开');
    }
  }
};


// 单个寄存器列表
const singleRegisters = computed(() => {
  return [...selectedRows.value].sort((a, b) => {
    return a[TableHeader.Address] - b[TableHeader.Address];
  });
});

const generateContinuousPairs = () => {
  // 提取地址并转换为数字，去重，然后按地址排序
  const sortedTableRow = [...selectedRows.value].sort((a, b) => {
    return a[TableHeader.Address] - b[TableHeader.Address];
  });
  const pairs = [];

  // 每次步进2，确保不重叠
  for (let i = 0; i < sortedTableRow.length - 1; i += 2) {
    if (sortedTableRow[i + 1][TableHeader.Address] === sortedTableRow[i][TableHeader.Address] + 1) {
      pairs.push([sortedTableRow[i], sortedTableRow[i + 1]]);
    }
  }

  return pairs;
};

// Long寄存器对列表
const longPairs = computed(() => {
  return generateContinuousPairs();
});

// Float寄存器对列表
const floatPairs = computed(() => {
  return generateContinuousPairs();
});

const openMessageDialog = () => {
  messageDialogRef.value?.openDialog();
};

// 在组件挂载时首次获取数据
onMounted(async () => {
  device.value = await deviceStore.getDevice(routeName.value);
  console.log(device.value);
});

// 监听路由变化
watch(
  () => route.name,
  async (newRouteName) => {
    if (newRouteName) {
      routeName.value = newRouteName as string;
      device.value = await deviceStore.getDevice(routeName.value);
    }
  }
);
</script>

<style scoped lang="scss">
.register-container {
  display: flex; /* 启用flex布局 */
  flex-wrap: nowrap; /* 禁止换行 */
  overflow-x: auto; /* 启用水平滚动 */
  gap: 16px; /* 设置元素间距 */
}

/* 水平滚动容器 */
.horizontal-scroll {
  height: 100%; /* 必须设置高度 */
  white-space: nowrap; /* 禁止内容换行 */
}

/* 样式穿透（Vue3使用:deep()） */
:deep(.el-scrollbar__wrap) {
  overflow-x: auto;
  display: flex !important;
}

.nodes {
  display: flex;
  flex-direction: row;
  gap: 20px; /* 选项之间的间距 */
  margin-left: 20px;
  align-items: center;
}

.register-view {
  margin-top: 10px;
  margin-left: 20px;
  margin-bottom: 10px;
}

.start-button {
  margin-top: 25px;
  width: 90px;
  height: 40px;
  padding: 10px;
  text-align: center;
  transition: background-color 0.3s ease; /* 添加背景色过渡效果 */
  .icon {
    font-size: 20px;
    vertical-align: middle;
  }

  .text {
    font-size: 16px;
    vertical-align: middle;
  }
}
</style>
